// pages/area/area.js
var app = getApp()
var header = {
  'content-type': 'application/x-www-form-urlencoded',
  'cookie': "openid=" + app.globalData.openid
}
var timer = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    btn_text:"修复",
    items: [],//列表
    choice: [],// 已选择
    setupflag: true,
    types: [],
    branch: [],//支路
    AREANAME:"",
    idx:'',
    mid:'',
    district:'',
    cur_item:'', //当前之路的
    cur_renovate:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // 页面初始化 options为页面跳转所带来的参数
    //var ob = wx.getStorageSync('area' + idx)
    let mid = options.mid
    let district = options.district

    that.setData({    
      mid:mid,
      district:district
    })
    wx.setNavigationBarTitle({
      title: district
    })
    //var array = ob.array
    //this.setData({ items: array, idx: idx })
    wx.request({
      url:app.globalData.url+'FindAllBranchDeviceInDepartment',
      type:"post",
      header:header,
      data:{
        departmentID:mid
      },
      success:res=>{
          //一个分支的输出{"result":"{\"0025015F\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道（三里村）\",\"gname\":\"沛龙大道(三里村)\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"002502AA\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"经四路北段\",\"gname\":\"经四路北段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false}]},\"0025015E\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道西段\",\"gname\":\"沛龙大道西段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025015C\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固大堤\",\"gname\":\"龙固大堤\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025015A\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"四海停车场\",\"gname\":\"四海停车场\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"0025016B\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"沛龙大道（龙固小加油站）\",\"gname\":\"沛龙大道（龙固小加油站）\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"00250160\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固镇委\",\"gname\":\"龙固镇委\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},\"002502A9\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"经四路南段\",\"gname\":\"经四路南段\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false}]},\"002502A4\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"龙固工业区\",\"gname\":\"龙固工业区\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]}}"}

          //另一个分支测试区域2的输出 {"result":"{\"002501B1\":{\"autoUnusual\":0,\"online\":false,\"dname\":\"本地测试\",\"gname\":\"测试路段\",\"branch\":[{\"port\":\"1\",\"switch\":false},{\"port\":\"0\",\"switch\":true}]}}"} 

          //3个例子
          //\"00250084\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"00250084\",\"gname\":\"东风西路西段路灯（汉润路-西环）\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false},{\"port\":\"4\",\"switch\":false}]},
          //\"00250083\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"00250083\",\"gname\":\"东风西路东段路灯（铁路-树人东）\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false}]},
          //\"00250082\":{\"autoUnusual\":1,\"online\":true,\"dname\":\"00250082\",\"gname\":\"东风西路中段路灯（树人-汉润路）\",\"branch\":[{\"port\":\"0\",\"switch\":false},{\"port\":\"1\",\"switch\":false},{\"port\":\"2\",\"switch\":false},{\"port\":\"3\",\"switch\":false}]},
          let res_json = res.data.result    
          let result = JSON.parse(res_json)
          // let devNoStrArr = []
          // let devNoStr = ""
          
          let dataArray = []

          //{AREANAME: "沛龙大道(三里村)",DEPTNAME: "沛县龙固镇",ID: 1526,IS_ONLINE: 1,POINT_NO: 4,SWITCH_STATUS: ["0", "0", "0", "0"],TERMINAL_ADDRESS:"0025015F"}
          if(result != {}){
            //取消按钮 无需组织设备号         
            for (let val in result) {              
              let templateJSON = {AREANAME: "",DEPTNAME: "",ID: "",IS_ONLINE: "",POINT_NO: "",SWITCH_STATUS: [],TERMINAL_ADDRESS:"",renovate_status:false,checkStatus:false}
              templateJSON.AREANAME = result[val].gname
              templateJSON.DEPTNAME = district
              // templateJSON.ID =  
              templateJSON.IS_ONLINE = result[val].online?1:0
              templateJSON.POINT_NO = result[val].branch.length
              templateJSON.checkStatus =  result[val].autoUnusual==1?true:false

              templateJSON.SWITCH_STATUS = ['--', '--', '--', '--']
              let switch_index = 0;
              //for(let i=0;i<5;i++){
                // if(result[val].branch[i] != undefined){

                //  
                //   templateJSON.SWITCH_STATUS[i-1] = result[val].branch[i].switch ? "1":"0"
                // }                  
              //}

              result[val].branch.forEach(function(branch_item, index){
                if(branch_item.port!=0){
                  templateJSON.SWITCH_STATUS[switch_index] = result[val].branch[index].switch ? "1":"0"
                  switch_index++
                }
              });
            
              //templateJSON.TERMINAL_ADDRESS = val
              templateJSON.TERMINAL_ADDRESS = result[val].mac

              dataArray.push(templateJSON);            
                      
              // if(result[val].online === true){
              //   devNoStrArr.push(val); //val 就是 \"002502A9\" 这些
              // } 
            }  
          }
         
          that.setData(
            {items: dataArray}
          )

          timer = setInterval(function () { 
            //console.log("reloadData area")
            that.reloadData()
          },10000)
      }
    })  },

  showSetup: function () {
    this.setData({ setupflag: false })
  },
  hideSetup: function () {
    this.setData({ types: [] })
    this.setData({ setupflag: true })
  },
  bindBatchChoose: function (e) {
    var items = e.detail.value
    var temp = []
    var types = this.data.types

    //items的值是这样的  ["total", "002502A701", "002502A702", "002502A703", "002502A704"]点击的获取到的check的value值集合
    if (items.length > 0) {
      if(items.indexOf("total")>=0){
        //这个是勾选了总路的
        temp.push("total")
        for(var i = 0; i < types.length; i++){
          if (i > 0) types[i].dis = true  //只要总路勾选了，其余的选项都不可用
        }
      }else{
        //这边是没有勾选总路的
        temp = items
        //var types = this.data.types
        for (var i = 0; i < types.length; i++) {
          if (i > 0) types[i].dis = false  //支路checkbox可用
          else types[i].dis = true  //总路checkbox变灰
        }
      }
      // if (items.indexOf("1") >= 0) {
      //   temp.push("1")
      //   for (var i = 0; i < types.length; i++) {
      //     if (i > 0) types[i].dis = true
      //   }
      // } else {
      //   temp = items
      //   var types = this.data.types
      //   for (var i = 0; i < types.length; i++) {
      //     if (i > 0) types[i].dis = false
      //     else types[i].dis = true
      //   }
      // }    
    } else {
      for (var i = 0; i < types.length; i++) {
        types[i].dis = false
      }
    }

    this.setData({ branch: temp, types: types})
  },
  //单击行弹出总路之路对话框
  bindChoice: function (e) {
    var that = this
    var item = e.currentTarget.dataset.ob  //{AREANAME: "测试1", DEPTNAME: "无锡测试", ID: "",IS_ONLINE: 1, POINT_NO: 4, SWITCH_STATUS: (4) ["1", "1", "0", "0"], TERMINAL_ADDRESS: "002502A7"}
    
    if (item.IS_ONLINE === 0) {
      wx.showToast({
        title: '离线设备不可用！',
        icon: 'error'
      })
      return;
    }
   
    var list2 = [item]
    // var types = [{ name: '一支路', value: 2 }, { name: '二支路', value: 3 }
    //   , { name: '三支路', value: 4 }, { name: '四支路', value: 5 }, { name: '五支路', value:6 },{ name: '六支路', value: 7 }]
    //var result = [{ name: '总路', value: 1 }]
    var types = [{ name: '一支路', value: item.TERMINAL_ADDRESS+"01" }, { name: '二支路', value:  item.TERMINAL_ADDRESS + "02" }
       , { name: '三支路', value:  item.TERMINAL_ADDRESS+"03" }, { name: '四支路', value:  item.TERMINAL_ADDRESS+"04" }, { name: '五支路', value: item.TERMINAL_ADDRESS+"05" },{ name: '六支路', value:  item.TERMINAL_ADDRESS+"06" }]
    var result = [{ name: '总路', value: "total"}]
   
    var switchs = item.SWITCH_STATUS
    for (var i = 0; i < switchs.length; i++) {
      //switch的值是["0", "0", "0", "0"] 或者["0", "0", "-", "-"]或者 ["1", "1", "-", "-"]或者["1", "1", "0", "0"]...
      if (switchs[i] != "--") {
        result.push(types[i])
      }
    }
    that.setData({ choice: list2, setupflag: false, types: result, AREANAME: item.AREANAME })
  },
  bingToKeep: function (e) {
    wx.showLoading({
      title:"请稍等..."
    })
    var that = this
    var opy = e.currentTarget.dataset.opy
    var cho = that.data.choice, nos = ''  //cho 也就是choice值是[{AREANAME: "测试1", DEPTNAME: "无锡测试", ID: "",IS_ONLINE: 1, POINT_NO: 4, SWITCH_STATUS: (4) ["1", "1", "0", "0"], TERMINAL_ADDRESS: "002502A7"}]
 
    if (cho.length == 0){
      wx.showModal({ title: '提示', content: "请选择操作终端号", showCancel: false })
      return
    }else{
      for(var i = 0; i < cho.length; i++){
        if (cho[i].IS_ONLINE == 0){
          wx.showModal({ title: '提示', content: "离线状态不能操作", showCancel: false })
          return
        }
        if (nos == '') {
          nos += cho[i].TERMINAL_ADDRESS
        } else {
          nos += ',' + cho[i].TERMINAL_ADDRESS
        }
      }
    }
   
    if (that.data.branch.length <= 0) {
      wx.showModal({ title: '提示', content: "请选择支路", showCancel: false })
      return
    }

    var branch_type = that.data.branch  // ["total"]或者["002502A701", "002502A702", "002502A703", "002502A704"]
   //console.log(branch_type, "branch_type");
    var url = ""
    var data = {}

    //总路
    if(branch_type.indexOf("total")!=-1){
      if(opy == "0"){//开灯
        url = app.globalData.url+"OpenBranchAll"
        data = {
          devNoList:cho[0].TERMINAL_ADDRESS
        }        
      }
      if(opy == "1"){//关灯
        url = app.globalData.url+"CloseBranchAll"
        data = {
          devNoList:cho[0].TERMINAL_ADDRESS
        }        
      }
    }    
    else{//支路
      if(opy == "0"){//开灯
        url = app.globalData.url+"addMission"
        data = {
          userid: app.globalData.userid,
          target: branch_type, //["002502A701", "002502A702", "002502A703", "002502A704"]
          type: 0
        }           
      }
      if(opy == "1"){//关灯
        url = app.globalData.url+"addMission"
        data = {
          userid: app.globalData.userid,
          target: branch_type, //["002502A701", "002502A702", "002502A703", "002502A704"]
          type: 1
        }        
      }
    }

    wx.request({
      header:header,   
      type:"post",
      url: url,
      data:data,
      success:res=>{             
        //console.log(res.data.error == 0, "res.data.error == 0")
        //总路开关返回
        if(branch_type.indexOf("total")!=-1){
          if(res.data.error == 0){
            wx.showToast({
              title:opy == "0"? '总路开操作成功':'总路关操作成功',
              icon: 'success',
              duration: 2000
            })

            //这个地方跟新一下设备的状态 
            let tmp_items = that.data.items
            tmp_items.forEach(function(subitem, index) {
              if(subitem.AREANAME == cho.AREANAME){
                if(opy == "0"){
                  subitem.SWITCH_STATUS = ["1","1","1","1"];
                }else{
                  subitem.SWITCH_STATUS = ["0","0","0","0"];
                }
              }
            })

            //新增刷新页面操作 这样总路开关就可以实时刷新显示
            // setTimeout(function () { 
            //   that.reloadData()
            // },5000)
          }
          if(res.data.error == -1){
            wx.showToast({
              title: opy == "0"? '总路开操作失败':'总路关操作失败',
              icon: 'error',
              duration: 2000
            })
          }
        }else{
          //支路开关返回
          if(res.data.error == 0){
            wx.showToast({
              title:"已加入任务队列,等待执行",
              icon: 'success',
              duration: 2000
            })
          }else{
            wx.showToast({
              title:"加入任务队列出错，请重新操作",
              icon: 'error',
              duration: 2000
            })
          }
        } 
        
        that.setData({setupflag:true})
      },
      complete: function () {
        wx.hideLoading()
      }
    })  
  },

  switchLight:function(e){
    var that = this
    wx.showLoading({
      title: '请稍等...',
    })
    //console.log(e, "switchLight e")
    
    //值是{currentTarget:dataset: {idx: "002500D5"},id: "",offsetLeft: 204,offsetTop: 55},detail: {value: true},mark: {},mut: false,dataset: {idx: "002500D5"},id: "",offsetLeft: 204,offsetTop: 55},timeStamp: 7007,type: "change"}
    // if(e.detail.value){
      wx.request({
        header:header,
        //url: app.globalData.url+"OpenBranchAll",
        url: app.globalData.url+"SetDeviceAutoUnusual",
        type:"post",
        data:{
          //devNoList:e.currentTarget.dataset.idx
          mac:e.currentTarget.dataset.idx,
          checked:e.detail.value
        },
        success:res=>{
          wx.hideLoading()           
          //console.log(res, "SetDeviceAutoUnusual")
          // if(res.data.error == 0){
          //   wx.showToast({
          //     title: '全开操作成功',
          //     icon: 'success',
          //     duration: 2000
          //   })
          //   setTimeout(function () {              
          //     that.reloadData()
          //     //需不断调用的操作
          //   }, 2000)           
          // }
          // if(res.data.error == -1){
          //   wx.showToast({
          //     title: '全开操作失败',
          //     icon: 'error',
          //     duration: 2000
          //   })
          // }                
        }
      })
    // }
    // if(!e.detail.value){
      //全关
      // wx.request({
      //   header:header,
      //   url: app.globalData.url+"CloseBranchAll",
      //   data:{
      //     devNoList:e.currentTarget.dataset.idx
      //   },
      //   success:res=>{
      //     wx.hideLoading()
      //     //console.log(res.data.error == 0, "res.data.error == 0")
      //     if(res.data.error == 0){
      //       wx.showToast({
      //         title: '全关操作成功',
      //         icon: 'success',
      //         duration: 2000
      //       })

      //       setTimeout(function () { 
      //       that.reloadData()
      //       },2000)
      //     }
      //     if(res.data.error == -1){
      //       wx.showToast({
      //         title: '全关操作失败',
      //         icon: 'error',
      //         duration: 2000
      //       })
      //     }
      //   }
      // })
    // }
  },

  emptyfunc:function() {
    
  },

  renovate:function(e){
    var that = this
 
    wx.showLoading({
      title: '请稍等...',
    })
    
    //值是{currentTarget:dataset: {idx: "002500D5"},id: "",offsetLeft: 204,offsetTop: 55},detail: {value: true},mark: {},mut: false,dataset: {idx: "002500D5"},id: "",offsetLeft: 204,offsetTop: 55},timeStamp: 7007,type: "change"}
    
      wx.request({
        header:header,
        //url: app.globalData.url+"OpenBranchAll",
        url: app.globalData.url+"SetDeviceAutoUnusual",
        type:"post",
        data:{
          //devNoList:e.currentTarget.dataset.idx
          mac:e.currentTarget.dataset.idx,
          checked:true
        },
        success:res=>{
          wx.hideLoading() 
          let tmp_items = that.data.items

          tmp_items.forEach(function(item, index){
            if(item.TERMINAL_ADDRESS == e.currentTarget.dataset.idx){
              item.renovate = true
            }
          })

          that.setData({
            items:tmp_items
          })                     
        },
        fail:error=>{
         
        }
      })        
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  reloadData:function(){
    var that = this
    wx.request({
      url:app.globalData.url+'FindAllBranchDeviceInDepartment',
      type:"post",
      header:header,
      data:{
        departmentID:that.data.mid
      },
      success:res=>{                  
          let res_json = res.data.result  
          //console.log(res_json)  
          let result = JSON.parse(res_json)
         
          let dataArray = []

          //{AREANAME: "沛龙大道(三里村)",DEPTNAME: "沛县龙固镇",ID: 1526,IS_ONLINE: 1,POINT_NO: 4,SWITCH_STATUS: ["0", "0", "0", "0"],TERMINAL_ADDRESS:"0025015F"}
          if(result != {}){
            //取消按钮 无需组织设备号         
            for (var val in result) {
              let templateJSON = {AREANAME: "",DEPTNAME: "",ID: "",IS_ONLINE: "",POINT_NO: "",SWITCH_STATUS: [],TERMINAL_ADDRESS:""}
              templateJSON.AREANAME = result[val].gname
              templateJSON.DEPTNAME = that.data.district
              // templateJSON.ID = 
              templateJSON.IS_ONLINE = result[val].online?1:0
              templateJSON.POINT_NO = result[val].branch.length

              templateJSON.SWITCH_STATUS = ['--', '--', '--', '--']
              for(let i=0;i<4;i++){
                if(result[val].branch[i] != undefined){
                  templateJSON.SWITCH_STATUS[i] = result[val].branch[i].switch ? "1":"0"
                }              
              }                 
              
              //templateJSON.TERMINAL_ADDRESS = val
              templateJSON.TERMINAL_ADDRESS = result[val].mac

              //后加的，用于页面的上的switch状态
              // if(templateJSON.SWITCH_STATUS.indexOf("0")!=-1){
              //   templateJSON.checkStatus = false
              // }else{
              //   templateJSON.checkStatus = true
              // }

              //{"002500D5":{"autoUnusual":1,"online":true,"dname":"测试9设备","gname":"测试9","branch":[{"port":"1","switch":true},{"port":"2","switch":true},{"port":"3","switch":true},{"port":"4","switch":true}]},"0025014D":{"autoUnusual":0,"online":true,"dname":"测试12设备","gname":"测试12","branch":[{"port":"1","switch":true},{"port":"2","switch":true},{"port":"3","switch":true},{"port":"4","switch":true}]},"0025016E":{"autoUnusual":0,"online":true,"dname":"测试11设备","gname":"测试11","branch":[{"port":"1","switch":true},{"port":"2","switch":true},{"port":"3","switch":true},{"port":"4","switch":true}]},"002500FB":{"autoUnusual":0,"online":true,"dname":"测试8设备","gname":"测试8","branch":[{"port":"1","switch":true},{"port":"2","switch":true},{"port":"3","switch":true},{"port":"4","switch":true}]},"002502A7":{"autoUnusual":0,"online":true,"dname":"测试1设备","gname":"测试1","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false}]},"002502BD":{"autoUnusual":1,"online":true,"dname":"测试7设备","gname":"测试7","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false}]},"002502BC":{"autoUnusual":1,"online":true,"dname":"测试5设备","gname":"测试5","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false}]},"002502BB":{"autoUnusual":1,"online":true,"dname":"测试6设备","gname":"测试6","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false}]},"002502BA":{"autoUnusual":1,"online":true,"dname":"测试4设备","gname":"测试4","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false},{"port":"0","switch":false}]},"00250185":{"autoUnusual":1,"online":true,"dname":"测试10设备","gname":"测试10","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false}]},"002502BF":{"autoUnusual":1,"online":true,"dname":"测试2设备","gname":"测试2","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false},{"port":"0","switch":false}]},"002502BE":{"autoUnusual":1,"online":true,"dname":"测试3设备","gname":"测试3","branch":[{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false},{"port":"0","switch":false}]},"00250148":{"autoUnusual":1,"online":true,"dname":"1","gname":"配电箱大","branch":[{"port":"0","switch":false},{"port":"1","switch":false},{"port":"2","switch":false},{"port":"3","switch":false},{"port":"4","switch":false}]}}
              if(result[val].autoUnusual == 0){
                templateJSON.checkStatus = false
              }else if(result[val].autoUnusual == 1){
                templateJSON.checkStatus = true
              }
             
              dataArray.push(templateJSON);    
            }  
          }  


          that.setData(
            {items: dataArray}
          )
        }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //console.log(" clearInterval(timer) already")
    clearInterval(timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //console.log(" clearInterval(timer) already")
    clearInterval(timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})